package edu.gxnu.cetcdemo.utils;

import com.auth0.jwt.JWT;
import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import edu.gxnu.cetcdemo.utils.Result;
import edu.gxnu.cetcdemo.pojo.User;
import edu.gxnu.cetcdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token
        String token = request.getHeader("token");

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        // 跳过带有 @PassToken注释 的令牌检查
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if(method.isAnnotationPresent(PassToken.class)){
            PassToken passToken = method.getAnnotation(PassToken.class);
            if(passToken.required()){
                return true;
            }
        }

        if(token == null){
            throw new TokenException(50001, "验证失败");
        }

        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException jwtDecodeException){
            throw new TokenException(50001, "验证失败");
        }

        User user = userService.getById(userId);
        if(user == null){
            throw new TokenException(50002, "用户未登录");
        }

        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("CetcServer")).build();
        try {
            jwtVerifier.verify(token);
        }catch (JWTVerificationException jwtVerificationException){
            throw new TokenException(50003, "验证失败");
        }

        return true;
    }
}
